package com.example.blogsystemssm.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 * 封装统一数据的返回
 * @ControllerAdvice @Component的派生类
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
//        return true才会执行下面的beforeBodyWrite方法?
        return true;
    }

    /**
     * @SneakyThrows 用来自动处理异常的
     * @return 返回给前端的 整体包装好的对象
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//        body已经是HashMap的情况下（说明已经封装好了）直接return
        if (body instanceof HashMap) {
            return body;
        }

//        String全走Ajax解析
        if (body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }

        return AjaxResult.success(body);
    }
}
